package com.qcby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcby.common.exception.BusinessException;
import com.qcby.entity.TLifeInfo;
import com.qcby.entity.TUser;
import com.qcby.form.TLifeInfoForm;
import com.qcby.form.TLifeInfoListForm;
import com.qcby.mapper.TLifeInfoMapper;
import com.qcby.mapper.TUserMapper;
import com.qcby.service.TLifeInfoService;
import com.qcby.vo.PageVO;
import com.qcby.vo.TLifeInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 生活资讯 服务实现类
 * </p>
 *
 * @author admin
 * @since 2025-02-04
 */
@Slf4j
@Service
public class TLifeInfoServiceImpl extends ServiceImpl<TLifeInfoMapper, TLifeInfo> implements TLifeInfoService {

    @Autowired
    private TLifeInfoMapper lifeInfoMapper;

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageVO<TLifeInfoVO> getLifeInfoList(TLifeInfoListForm form) {
        Page<TLifeInfo> page = new Page<>(form.getPage(), form.getLimit());
        
        QueryWrapper<TLifeInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(form.getTitle()), "title", form.getTitle())
                .eq(form.getType() != null, "type", form.getType())
                .eq(StringUtils.hasText(form.getStatus()), "status", form.getStatus())
                .eq("is_deleted", 0)
                .orderByDesc("create_time");
                
        Page<TLifeInfo> resultPage = lifeInfoMapper.selectPage(page, queryWrapper);
        
        List<TLifeInfoVO> voList = new ArrayList<>();
        for (TLifeInfo info : resultPage.getRecords()) {
            voList.add(convertToVO(info));
        }
        
        return new PageVO<>(voList, resultPage.getTotal(), form.getPage(), form.getLimit());
    }

    @Override
    @Transactional
    public void addLifeInfo(TLifeInfoForm form) {
        TLifeInfo info = new TLifeInfo();
        BeanUtils.copyProperties(form, info);
        
        info.setStatus("未推送");
        info.setCreateTime(LocalDateTime.now());
        info.setUpdateTime(LocalDateTime.now());
        info.setIsDeleted(0);
        
        lifeInfoMapper.insert(info);
    }

    @Override
    @Transactional
    public void updateLifeInfo(Integer id, TLifeInfoForm form) {
        TLifeInfo info = checkLifeInfoExists(id);
        
        // 检查状态是否允许修改
        if (!"未推送".equals(info.getStatus()) && !"推送异常".equals(info.getStatus())) {
            throw new BusinessException("当前状态不允许修改");
        }
        
        BeanUtils.copyProperties(form, info);
        info.setUpdateTime(LocalDateTime.now());
        
        lifeInfoMapper.updateById(info);
    }

    @Override
    @Transactional
    public void deleteLifeInfo(Integer id) {
        TLifeInfo info = checkLifeInfoExists(id);
        
        // 检查状态是否允许删除
        if (!"未推送".equals(info.getStatus()) && !"推送异常".equals(info.getStatus())) {
            throw new BusinessException("当前状态不允许删除");
        }
        
        info.setIsDeleted(1);
        info.setUpdateTime(LocalDateTime.now());
        
        lifeInfoMapper.updateById(info);
    }

    @Override
    @Transactional
    public void pushLifeInfo(Integer id) {
        TLifeInfo info = checkLifeInfoExists(id);
        
        if (!"未推送".equals(info.getStatus()) && !"推送异常".equals(info.getStatus())) {
            throw new BusinessException("当前状态不允许推送");
        }
        
        try {
            // 查询所有用户
            List<TUser> users = userMapper.selectList(new QueryWrapper<TUser>().eq("is_deleted", 0));
            
            // 开始推送
            info.setStatus("推送中");
            info.setUpdateTime(LocalDateTime.now());
            lifeInfoMapper.updateById(info);
            
            // 通过消息队列推送给所有用户
            for (TUser user : users) {
                rabbitTemplate.convertAndSend("life_info_exchange", "life_info_routing_key", 
                    new PushMessage(info.getInfoId(), user.getUserId()));
            }
            
            // 更新推送状态
            info.setStatus("已推送");
            info.setPushTime(LocalDateTime.now());
            info.setUpdateTime(LocalDateTime.now());
            lifeInfoMapper.updateById(info);
            
        } catch (Exception e) {
            log.error("推送生活资讯失败", e);
            // 更新为推送异常状态
            info.setStatus("推送异常");
            info.setPushError(e.getMessage());
            info.setUpdateTime(LocalDateTime.now());
            lifeInfoMapper.updateById(info);
            
            throw new BusinessException("推送失败：" + e.getMessage());
        }
    }

    @Override
    public TLifeInfoVO getLifeInfoDetail(Integer id) {
        TLifeInfo info = checkLifeInfoExists(id);
        return convertToVO(info);
    }

    private TLifeInfo checkLifeInfoExists(Integer id) {
        TLifeInfo info = lifeInfoMapper.selectById(id);
        if (info == null || info.getIsDeleted() == 1) {
            throw new BusinessException("生活资讯不存在");
        }
        return info;
    }

    private TLifeInfoVO convertToVO(TLifeInfo info) {
        TLifeInfoVO vo = new TLifeInfoVO();
        BeanUtils.copyProperties(info, vo);
        // 设置类型名称等其他信息
        return vo;
    }
}
